package trace

import (
	"fmt"
	"go.opentelemetry.io/otel"
	// nolint
	"go.opentelemetry.io/otel/exporters/jaeger"
	"go.opentelemetry.io/otel/sdk/resource"
	"go.opentelemetry.io/otel/sdk/trace"
	semconv "go.opentelemetry.io/otel/semconv/v1.21.0"
	"os"
)

// InitGlobalTracer 初始化全局链路追踪
func InitGlobalTracer(url string, sampler float64, appName, appVersion string) {
	exporter, err := jaeger.New(jaeger.WithCollectorEndpoint(jaeger.WithEndpoint(url)))
	if err != nil {
		panic(fmt.Errorf("failed to initialize jaeger exporter:%s", url))
	}
	hostName, _ := os.Hostname()
	tp := trace.NewTracerProvider(
		// 将基于父span的采样率设置为100%
		trace.WithSampler(trace.ParentBased(trace.TraceIDRatioBased(sampler))),
		// 始终确保在生产中批量处理
		trace.WithBatcher(exporter),
		// 在资源中记录有关此应用程序的信息
		trace.WithResource(resource.NewSchemaless(
			semconv.ServiceNameKey.String(appName),
			semconv.ServiceVersionKey.String(appVersion),
			semconv.ServiceInstanceIDKey.String(hostName),
			semconv.GCPGceInstanceHostnameKey.String(hostName),
		)),
	)
	otel.SetTracerProvider(tp)
}
